﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.BLL.WorkProcess;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Frm.NodeTree;
using Ledict.ConditionExtract.Model;
using Ledict.Regex.BLL;
using Ledict.Utility.Extension;
using Ledict.Utility.Frm;
using Ledict.Utility.Frm.Model;
using Ledict.Utility.Frm.Process;
using Ledict.Utility.Helper;
using Ledict.Utility.Msg;
using System.Text;
using System.Xml;
using System.Reflection;
using System.IO;
using Ledict.Regex.Model;

namespace Ledict.ConditionExtract
{
    /// <summary>
    /// 节点树操作界面
    /// </summary>  
    public partial class NodeTreeAnalysis : BaseForm
    {
        #region 构造单例
        //静态锁
        private static readonly object Lock = new object();
        /// <summary>
        /// 单例
        /// </summary>
        private static NodeTreeAnalysis _instance;
        /// <summary>
        /// 返回单例
        /// </summary>
        public static NodeTreeAnalysis Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (Lock)
                    {
                        if (_instance == null || _instance.IsDisposed)
                        {
                            _instance = new NodeTreeAnalysis();
                        }
                    }
                }
                return _instance;
            }

        }

        public NodeTreeAnalysis()
        {
            InitializeComponent();
            //要素属性xml界面左下角gridView
            dataGridView1.AutoGenerateColumns = dataGridView2.AutoGenerateColumns = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = dataGridView2.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            ShowIcon = false;
        }
        #endregion

        #region 共有变量
        List<TreeNode> NodeList = new List<TreeNode>();
        readonly TreeDataBLL trbll = new TreeDataBLL();
        public string FirId = "1477";//默认民事树
        TreeNode editnode = new TreeNode();
        private CaseCauseBLL casecausebLL = new CaseCauseBLL();
        private TreeNode clicknode;//点击节点树后，保存该节点
        DataTable dtNew = new DataTable();
        private bool IsZhankai = false;
        private DataTable dtCase;
        #endregion

        #region 界面加载
        /// <summary>
        /// 初始化节点树、案由树、法院树等等
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NodeTree_Load(object sender, EventArgs e)
        {
            CaseCauseTree();//节点树  
            lblCount.Visible = progressBar1.Visible = true;
            //SA_Id,SA_TextValue,SA_CaseNumber,SA_BookLogicalCode,SA_BookLogicalCode,case SA_CheckState when 0 then 'false' when 1 then 'true' else 'false' end as SA_CheckState,SA_TextID
            dtNew.Columns.AddRange(new DataColumn[] { new DataColumn() { ColumnName = "SA_Id" }, new DataColumn() { ColumnName = "SA_TextValue" }, new DataColumn() { ColumnName = "SA_CaseNumber" }, new DataColumn() { ColumnName = "SA_CheckState" }, new DataColumn() { ColumnName = "SA_TextID" } });
            //progressBar1.Text ="1111";
            //lblCount.Text = "当前" + 2 + "条";
            dtCase = casecausebLL.GetArgumentFocusCase();
        }
        #endregion

        #region 左侧树

        #region 定位（树未用）
        /// <summary>
        /// 定位
        /// </summary>
        /// <param name="id"></param>
        private void ToLocateNode(string id)
        {
            SYS_CaseCause caseCause = casecausebLL.GetCaseCauseByCCID(id);
            if (caseCause.AllParentId != null)
            {
                var notePidArr = caseCause.AllParentId.Split(',');
                for (var i = 0; i < notePidArr.Length; i++)
                {
                    if (i != notePidArr.Length - 1)
                    {
                        FindNode(notePidArr[i]).Expand();
                    }
                    else
                    {
                        var node = FindNode(notePidArr[i]);
                        node.ForeColor = Color.Green;
                        //tVCaseCause.SelectedNode = node;

                    }
                }
            }
        }
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public void CaseCauseTree()
        {
            #region 初始化
            tVCaseCause.Nodes.Clear();
            NodeList.Clear();
            MaxCount.Text = "";
            CurrentCount.Text = "";
            SkipNumber.Text = "";
            #endregion
            var dt = trbll.NodeTree_Tree("");//第一层的树
            var arrayDr = dt.Select("name='民事案由'");//找出“刑事罪名”的节点
            foreach (var caseTreeNodeRode in arrayDr)
            {
                var node = new TreeNode();
                //节点名称
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode[1]);
                //节点id
                node.Tag = caseTreeNodeRode[0];
                //节点type
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode[2]);
                // FirId = caseTreeNodeRode[0].ToString();
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)//节点有没有下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                tVCaseCause.Nodes.Add(node);//父级节点添加节点
                //if (caseTreeNodeRode["CC_CommonCase"].ToString() == "1" && ISCommonCase == 1)//同案节点标颜色
                //    node.ForeColor = Color.Blue;
                NodeList.Add(node);//list用来查询
            }
            if (tVCaseCause.Nodes.Count > 0)
                tVCaseCause.SelectedNode = tVCaseCause.Nodes[0];
        }
        #endregion

        #region 下级树
        /// <summary>
        /// 下级树
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();// 父级ID
            var caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            {
                var node = new TreeNode();
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
                if (trbll.NodeTree_Tree(node.Tag.ToString()).Rows.Count > 0)//节点有无下级
                {
                    node.Nodes.Add(new TreeNode());
                }
                if (IsZhankai && node.Name == "16")
                {
                    if (dtCase != null && dtCase.Rows.Count > 0)
                    {
                        if (dtCase.Select("SA_RelevanceCaseID='" + node.Tag.ToString() + "'").Length > 0)
                        {
                            node.ForeColor = Color.Blue;
                        }
                    }
                    //tVCaseCause.AfterExpand -= tVCaseCause_AfterExpand;
                    //tVCaseCause.AfterExpand += tVCaseCause_AfterExpand;
                }
                //if (caseTreeNodeRode.Rows[i]["CC_CommonCase"].ToString() == "1" && ISCommonCase == 1)//同案节点标颜色
                //    node.ForeColor = Color.Blue;
                parentNode.Nodes.Add(node);//父级节点添加节点
                TreeNode node1 = null;
                foreach (var node2 in NodeList)//遍历现在界面上的所有节点
                {
                    if (node2.Tag.ToString() == node.Tag.ToString())
                    {
                        node1 = node2;
                        break;
                    }
                }
                if (node1 != null)
                {
                    NodeList.Remove(node1);
                    NodeList.Add(node);//list用来查询
                }
                else
                {
                    NodeList.Add(node);
                }

            }
        }
        #endregion

        #region 左侧树展开事件
        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            CaseCauseTreeChild(e.Node);

        }
        #endregion

        #region 左侧节点树选中事件
        /// <summary>
        /// 左侧节点树选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (clicknode != null)
            {
                if (e.Node != null)
                {
                    if (clicknode.Text != e.Node.Text)
                    {
                        clicknode.ForeColor = Color.Black;
                    }
                }
            }
            if (e.Node != null)
            {
                clicknode = e.Node;//保存节点
                                   //根据ccid控制添加子节点、同级节点菜单显示             
                                   // if (clicknode.ForeColor != Color.Blue)
                clicknode.ForeColor = Color.Red;
                //    ColorCommonCase_Click(nul);
                DataTable dt = casecausebLL.GetArgumentFocus(clicknode.Tag.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    ///MS_CR_ArgumentFocus   MS_CR_DefendantSuggest
                    DataTable dtFocus = dt.Select("SA_BookLogicalCode='MS_CR_ArgumentFocus'").Count<DataRow>() > 0 ? dt.Select("SA_BookLogicalCode='MS_CR_ArgumentFocus'").CopyToDataTable<DataRow>() : new DataTable();
                    DataTable dtSuggest = dt.Select("SA_BookLogicalCode='MS_CR_DefendantSuggest'").Count<DataRow>() > 0 ? dt.Select("SA_BookLogicalCode='MS_CR_DefendantSuggest'").CopyToDataTable<DataRow>() : new DataTable();
                    if (dtFocus != null && dtFocus.Rows.Count > 0)
                    {
                        dataGridView1.DataSource = dtFocus;
                    }
                    if (dtSuggest != null && dtSuggest.Rows.Count > 0)
                    {
                        dataGridView2.DataSource = dtSuggest;
                    }
                }
                else
                {
                    dataGridView1.DataSource = dataGridView2.DataSource = dtNew;
                }
            }
        }
        #endregion

        #endregion


        #region 编辑案由树节点

        #region 节点树鼠标按下事件
        /// <summary>
        /// 节点树鼠标按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            var clickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(clickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                SYS_CaseCause objCaseCause = casecausebLL.GetCaseCauseByCCID(editnode.Tag.ToString());
                if (objCaseCause != null)
                {
                    tVCaseCause.SelectedNode = editnode;//选中这个节点
                }
            }
        }
        #endregion



        #region 全部展开
        /// <summary>
        /// 全部展开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AllExpandMenuItem_Click(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }
        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="pid"></param>
        private void AllExpandNode(string pid)
        {
            var findNode = FindNode(pid);
            if (findNode != null) findNode.ExpandAll();
        }
        #endregion


        #region 查询节点
        DataTable Querydt;//查询结果集
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeBtn_Click(object sender, EventArgs e)//查询
        {
            QueryNode();
        }

        /// <summary>
        /// 回车查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')//回车
            {
                QueryNode();
            }
        }

        /// <summary>
        /// 下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!string.IsNullOrEmpty(CurrentCount.Text))
            {
                CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) + 1).ToString();//下一条
                SkipNumber.Text = CurrentCount.Text;
                var CurrNode = Convert.ToInt32(CurrentCount.Text);
                QueryNode_Page(Querydt, CurrNode);//定位查询
                LinkIsVisible(CurrNode);
            }
        }

        /// <summary>
        /// 上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (!String.IsNullOrEmpty(CurrentCount.Text))
            {
                CurrentCount.Text = (Convert.ToInt32(CurrentCount.Text) - 1).ToString();//上一条
                SkipNumber.Text = CurrentCount.Text;
                var CurrNode = Convert.ToInt32(CurrentCount.Text);
                QueryNode_Page(Querydt, CurrNode);//定位查询
                LinkIsVisible(CurrNode);
            }
        }

        /// <summary>
        /// 上一条下一条是否可用
        /// </summary>
        /// <param name="CurrNode"></param>
        private void LinkIsVisible(int CurrNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (CurrNode <= 1)//当前小于1
            {
                Prelinkbtn.Enabled = false;//上一页不可用
            }
            if (CurrNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;//下一页不可用
            }
        }

        /// <summary>
        /// 跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            var CurrNode = Convert.ToInt32(SkipNumber.Text);//当前节点条数
            if (Querydt != null && !string.IsNullOrEmpty(QueryNodeTxt.Text.Trim()))
            {
                if (Querydt.Rows.Count >= CurrNode)
                {
                    CurrentCount.Text = SkipNumber.Text;//跳转
                    QueryNode_Page(Querydt, CurrNode);//定位到目标节点
                    LinkIsVisible(CurrNode);// 上一条下一条是否可用
                }
                else
                {
                    MessageBox.Show("跳转页码有误，重新输入！");
                }
            }
        }

        /// <summary>
        /// 开始查询
        /// </summary>
        private void QueryNode()
        {
            var QueryNodeName = QueryNodeTxt.Text.Trim();//查询关键字
            if (QueryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, QueryNodeName, 1);//查询结果
                MaxCount.Text = Querydt.Rows.Count.ToString();//总数
                if (Querydt.Rows.Count > 0)
                {
                    CurrentCount.Text = "1";//当前节点条数
                    SkipNumber.Text = CurrentCount.Text;//跳转文本框
                    var CurrNode = Convert.ToInt32(CurrentCount.Text);//当前节点条数
                    LinkIsVisible(CurrNode);//上一条下一条是否可用
                    QueryNode_Page(Querydt, CurrNode);//定位到目标节点
                }
                else
                {
                    CurrentCount.Text = "0";//没结果
                    SkipNumber.Text = CurrentCount.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }


        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex && showindex > 0)
            {
                var NotePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');//所有父级
                for (var i = 0; i < NotePidArr.Length; i++)
                {
                    if (i != NotePidArr.Length - 1)
                    {
                        var Node = FindNode(NotePidArr[i]);
                        if (Node != null)
                        {
                            Node.Expand();//拖出所有父级节点
                        }
                    }
                    else  //最后一级节点为查找节点
                    {
                        var node = FindNode(NotePidArr[i]);
                        tVCaseCause.SelectedNode = node;//定位          
                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }
        }
        //  clicknode.ForeColor = Color.Blue;

        /// <summary>
        /// 查找节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (var node in NodeList)//遍历现在界面上的所有节点
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;
            //return (TreeNode)NodeList[Nodeid];
        }

        #endregion


        #endregion

        #region 右侧
        #region     点击左边节点 显示右侧界面

        #region 标签页切换
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                //诉请与要素关系配置插页  第十一个插页
                case "tab_XmlLabel_SuitTypeRel":
                    //ShowSuitTypeList(clicknode.Tag.ToString());
                    break;
                //提取规则
                case "Tab_Extract":
                    ShowTab_Extract();
                    break;
            }
        }
        #endregion

        #region 提取规则标签页
        /// <summary>
        /// 提取规则标签页
        /// </summary>
        private void ShowTab_Extract()
        {
            //if (casecausebLL.IsCivilCase(clicknode.Tag.ToString()))
            //{
            //    一键添加ToolStripMenuItem1.Enabled = true;
            //    if (clicknode.Name == "2" && casecausebLL.IsLastAnYou(clicknode.Tag.ToString()))
            //    {
            //        //导入导出规则
            //        btnRuleIn.Visible = btnRuleOut.Visible = true;
            //    }
            //    else
            //    {
            //        btnRuleIn.Visible = btnRuleOut.Visible = false;
            //    }
            //}
            //else
            //{
            //    一键添加ToolStripMenuItem1.Enabled = false;
            //    btnRuleIn.Visible = btnRuleOut.Visible = false;
            //}
            //ShowSource(clicknode.Tag.ToString());//显示来源
            //webBrowser1.Url = null;//正则
        }
        #endregion


        #endregion


        #endregion

        #region 接口方法

        // 显示进度条
        // 显示进度条
        public void ShowProgress(int MaxCount, int CurrentCount)
        {
            if (this.InvokeRequired == false)
            {
                if (CurrentCount < MaxCount)
                {
                    progressBar1.Value = CurrentCount;
                    progressBar1.Maximum = MaxCount;

                    progressBar1.Text = CurrentCount + "/" + MaxCount;
                    lblCount.Text = "当前" + CurrentCount + "条";
                }
                else if (CurrentCount == MaxCount)
                {
                    progressBar1.Value = CurrentCount;
                    progressBar1.Maximum = MaxCount;
                    progressBar1.Text = CurrentCount + "/" + MaxCount;
                    lblCount.Text = "已完成!";
                }
            }
            else
            {
                ProcessShow processshow = ShowProgress;
                Invoke(processshow, MaxCount, CurrentCount);
            }

        }

        #endregion


        #region 将字符串转换为XML格式字符串
        /// <summary>
        /// 将字符串转换为XML格式字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string FormatXML(string str)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(str);
            StringBuilder strbu = new StringBuilder();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(strbu);
            System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(stringWriter);
            xmlWriter.Formatting = System.Xml.Formatting.Indented;
            doc.WriteTo(xmlWriter);
            return strbu.ToString();
        }
        #endregion


        #region 跳转输入框只能输入数字
        /// <summary>
        /// 跳转输入框只能输入数字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SkipNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
            {
                e.Handled = true;
            }
        }


        #endregion

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                if (e.ColumnIndex == 2)
                {
                    var checkCellRight = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells["analysisState"];
                    string saID = dataGridView2.Rows[e.RowIndex].Cells[3].ToString();

                    if (Convert.ToBoolean(checkCellRight.Value))
                    {
                        checkCellRight.Value = false;
                        casecausebLL.UpdateArgumentFocusState(0, saID);
                    }
                    else
                    {
                        checkCellRight.Value = true;
                        casecausebLL.UpdateArgumentFocusState(1, saID);
                    }
                }
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                if (e.ColumnIndex == 2)
                {
                    DataGridViewCheckBoxCell checkCellRight = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells[2];
                    string saID = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();

                    if (Convert.ToBoolean(checkCellRight.Value))
                    {
                        checkCellRight.Value = false;
                        casecausebLL.UpdateArgumentFocusState(0, saID);
                    }
                    else
                    {
                        checkCellRight.Value = true;
                        casecausebLL.UpdateArgumentFocusState(1, saID);
                    }
                }
            }
        }
        Thread workThread1;
        bool isUpate = false;

        private void button1_Click(object sender, EventArgs e)
        {
            if (workThread1 != null && workThread1.IsAlive)
            {

                lblCount.Visible = progressBar1.Visible = false;
            }
            else
            {
                lblCount.Visible = progressBar1.Visible = true;
                workThread1 = new Thread(NewMethod);
                workThread1.Start();
            }

        }

        private void NewMethod()
        {
            //lblCount.Visible = progressBar1.Visible = true;

            Dictionary<string, string> dic = new Dictionary<string, string>();
            Dictionary<string, string> dic1 = new Dictionary<string, string>();
            //先获取需要处理的数据
            DataTable dt1 = casecausebLL.GetArgumentFocusDispose();
            DataTable dt = casecausebLL.GetArgumentFocusDispose1();

            if (dt1 != null && dt1.Rows.Count > 0 && dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    StringBuilder sb = new StringBuilder();
                    StringBuilder sb1 = new StringBuilder();
                    if (dt1.Select(" SA_TextID='" + dr["SA_TextID"].ToString() + "'").Length > 0)
                    {
                        DataTable dt2 = dt1.Select(" SA_TextID='" + dr["SA_TextID"].ToString() + "'").CopyToDataTable<DataRow>();
                        foreach (DataRow item in dt2.Rows)
                        {
                            SYS_CaseCause casec = casecausebLL.GetCaseCauseByCCID(item["SA_RelevanceCaseID"].ToString());
                            sb.Append(item["SA_RelevanceCaseID"].ToString() + "(" + casec.CC_Name + ")" + ",");
                            sb1.Append(item["SA_RelevanceCaseID"].ToString() + ",");
                        }
                        dic.Add(dr["SA_TextID"].ToString(), sb.ToString().Remove(sb.ToString().Length - 1, 1));
                        dic1.Add(dr["SA_TextID"].ToString(), sb1.ToString().Remove(sb1.ToString().Length - 1, 1));
                    }
                }
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = dt.Rows.Count;
                int i = 1;
                StringBuilder sb = new StringBuilder();
                string message = "";
                AnalysisArgumentFocus.AnalysisMain analysisMain = new AnalysisArgumentFocus.AnalysisMain();
                AnalysisArgumentFocus.AnalysisMain.CommonConnection = "Data Source=192.168.1.52;Initial Catalog=LdtCommonManage;User ID=sa;Password=ldtlaw_123";
                AnalysisArgumentFocus.AnalysisMain.SystemConnection = "Data Source=192.168.1.52;Initial Catalog=Ldt_JudgeDocSystem;User ID=sa;Password=ldtlaw_123";
                foreach (DataRow dr in dt.Rows)
                {
                    string orginaltext = dr["SA_TextValue"].ToString().Trim();
                    string caseID = dr["SA_CaseID"].ToString();
                    string flBookType = dr["SA_BookTypeCode"].ToString();
                    string lpCode = dr["SA_BookLogicalCode"].ToString();
                    string TCaseCode = dr["SA_CaseNumber"].ToString();
                    string FT_ID = dr["SA_TextID"].ToString();
                    Dictionary<string, string> listvalue = analysisMain.GetArgumentFocus(orginaltext, caseID, flBookType, lpCode, out message);
                    if (message.Contains("成功"))
                    {

                        if (listvalue.Count > 0)
                        {

                            casecausebLL.DeleteArgumentFocusByTextID(FT_ID, caseID);
                            StringBuilder sb1 = new StringBuilder();
                            ArgumentFocus model = new ArgumentFocus();
                            foreach (var messagedic in listvalue)
                            {
                                model.SA_Id = Guid.NewGuid().ToString();
                                model.SA_CaseID = caseID;
                                model.SA_BookTypeCode = flBookType;
                                model.SA_BookLogicalCode = lpCode;
                                model.SA_TextValue = orginaltext;
                                model.SA_TextID = FT_ID;
                                model.SA_CaseNumber = TCaseCode;
                                model.SA_RelevanceCaseID = messagedic.Key;
                                sb1.Append(messagedic.Key + ",");
                                if (dic.ContainsKey(FT_ID))
                                {
                                    string[] str = dic[FT_ID].Split(',');
                                    foreach (string item in str)
                                    {
                                        if (model.SA_RelevanceCaseID == item)
                                        {
                                            model.SA_CheckState = 1;
                                        }
                                    }
                                }
                                //Console.WriteLine(messagedic.Key + "---" + messagedic.Value + "---" + orginaltext);
                                casecausebLL.AddArgumentFocus(model);
                            }
                            if (dic.ContainsKey(FT_ID))
                            {
                                string dd = sb1.ToString().Remove(sb1.ToString().Length - 1, 1);
                                if (dic1[FT_ID].ToString() != dd)
                                {
                                    sb.Append("时间 " + DateTime.Now.ToString() + " 文本内容：" + orginaltext + " 文本id：" + FT_ID + " 原来关联ID：" + dic1[FT_ID] + " 修改为：");
                                    sb.Append(sb1.ToString().Remove(sb1.ToString().Length - 1, 1) + " \r\n");
                                }
                            }

                            //获得文件路径  "E:/工作/Expressluceneindex
                            string localFilePath = @"D:\争议焦点日志文件\" +
               DateTime.Now.Year + '-' +
               DateTime.Now.Month + '-' +
               DateTime.Now.Day + "_ArgumentFocus.log";
                            if (Directory.Exists(Path.GetDirectoryName(localFilePath)) == false)//如果不存在就创建file文件夹
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(localFilePath));
                            }
                            if (!string.IsNullOrEmpty(sb.ToString().Trim()))
                            {
                                if (!File.Exists(localFilePath))
                                {
                                    ShowProgress("有更新");
                                    StreamWriter sw = new StreamWriter(localFilePath, true, Encoding.Unicode);
                                    sw.WriteLine(sb.ToString().Trim());
                                    sw.Close();
                                }
                                else
                                {
                                    ShowProgress("有更新");
                                    StreamWriter sw = new StreamWriter(localFilePath, true, Encoding.Unicode);
                                    sw.WriteLine(sb.ToString().Trim());
                                    sw.Close();
                                }
                            }
                        }
                    }
                    ShowProgress(max, i);
                    i++;
                }
                //lblCount.Visible = progressBar1.Visible = false;
                dtCase = casecausebLL.GetArgumentFocusCase();

            }
        }

        public void ShowProgress(string str)
        {
            if (label1.InvokeRequired)
            {
                // 当一个控件的InvokeRequired属性值为真时，说明有一个创建它以外的线程想访问它
                Action<string> actionDelegate = (x) => { this.label1.Text = x.ToString(); };
                // 或者
                // Action<string> actionDelegate = delegate(string txt) { this.label2.Text = txt; };
                this.label1.Invoke(actionDelegate, str);
            }
        }

        /// <summary>
        /// 双击列反选节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                string saTextID = dataGridView2.Rows[e.RowIndex].Cells[4].ToString();
                DataTable dt = casecausebLL.GetArgumentFocusCaseID(saTextID);
                if (dt != null && dt.Rows.Count > 1)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        ToLocateNode(item["SA_RelevanceCaseID"].ToString());
                    }
                }
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                string saTextID = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
                DataTable dt = casecausebLL.GetArgumentFocusCaseID(saTextID);
                if (dt != null && dt.Rows.Count > 1)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        ToLocateNode(item["SA_RelevanceCaseID"].ToString());
                    }
                }
            }
        }

        /// <summary>
        /// 一键展开功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 一键展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (editnode != null)
            {
                var findNode = FindNode(editnode.Tag.ToString());
                if (findNode != null)
                {
                    IsZhankai = true;
                    findNode.ExpandAll();
                    IsZhankai = false;
                }
            }
        }

        /// <summary>
        /// 打开日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            label1.Text = "";
            string v_OpenFolderPath = @"D:\争议焦点日志文件\";
            System.Diagnostics.Process.Start("explorer.exe", v_OpenFolderPath);
        }

        private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex>-1)  //编辑文本
            {
                textBox1.Text = dataGridView2.Rows[e.RowIndex].Cells[0].Value.ToString();
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)  //编辑文本
            {
                richTextBox1.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            }
        }
    }

   

}